package com.china08.yxyapi.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.config.RabbitConfig;
import com.china08.yxyapi.util.JpushForMessageUtil.JpushForCompRespModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 发送推送:[消息通知]
 * 
 */
public class JpushForNotificationUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JpushForNotificationUtil.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    private static RestTemplate restTemplate;

    public static void sendNotification(String alert, String title, Map<String, String> extra, List<String> tags,
            List<String> tag_ands) {
        Map<String, String> returnMap = new HashMap<String, String>();

        String yxyApiYxUrl = SpringContextUtil.getCtx().getEnvironment().getProperty("yx.rest.api.yx.path");

        // 通知内容
        if (null == alert) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        if (alert.isEmpty()) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        String abbrAlert = StringUtils.abbreviate(alert, 50);

        returnMap.put("ALERT", abbrAlert);

        // 通知标题
        if (null == title) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        if (title.isEmpty()) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        returnMap.put("TITLE", title);

        // 验证推送开关是否开启
        String modelId = extra.get("modelId");

        List<Integer> role = new ArrayList<Integer>();
        for (String ta : tag_ands) {
            StringBuffer roleBuffer = new StringBuffer();
            // 转为char数组
            char[] ch = ta.toCharArray();
            // 得到大写字母
            for (int i = 0; i < ch.length; i++) {
                if (ch[i] >= 'A' && ch[i] <= 'Z') {
                    roleBuffer.append(ch[i]);
                }
            }
            switch (roleBuffer.toString()) {
            case "SCH":
                role.add(2);
                break;
            case "TEACHER":
                role.add(0);
                break;
            case "PARENTS":
                role.add(1);
                break;
            default:
                return;
            }
        }

        // 获取推送开关是否开启&能否发送推送
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("jpushName", modelId);
            formMap.put("jpushRole", role);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            restTemplate = new RestTemplate();
            JpushForCompRespModel httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/jpush/comp/app/switch",
                    formEntity, JpushForCompRespModel.class);

            if (!httpResult.isTure) { return; }
        } catch (Exception e) {
            LOGGER.info("获取推送开关接口异常：" + e.getMessage());
        }

        // 通知拓展数据
        String extraJson = "";

        try {
            extraJson = objectMapper.writeValueAsString(extra);
        } catch (JsonProcessingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            LOGGER.info("发送取消: 组装数据异常");
        }
        returnMap.put("EXTRA", extraJson);

        // tag用户
        if (null == tags) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }
        if (tags.isEmpty()) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }

        // tag_and数据
        if (null != tag_ands) {
            if (!tag_ands.isEmpty()) {
                if (tag_ands.size() > 20) {
                    LOGGER.info("发送取消: tags_and参数");
                    return;
                }
                returnMap.put("msgTag_and", StringUtils.join(tag_ands.toArray(), ","));
            }
        }

        returnMap.put("msgReceivers", StringUtils.join(tags.toArray(), ","));

        try {
            SpringContextUtil.getBean(RabbitTemplate.class).convertAndSend(RabbitConfig.JPUSH_FOR_NOTIFICATION,
                    returnMap);
        } catch (AmqpException e) {
            LOGGER.info("发送准备失败: RabbitMQ发送失败");
            return;
        }
        LOGGER.info("发送准备完毕: 通知消息数据组装成功，准备发送");
    }

    /**
     * 定时推送
     */
    public static void sendNotificationTiming(String alert, String title, Map<String, String> extra, List<String> tags,
            List<String> tag_ands, Date date) {
        Map<String, String> returnMap = new HashMap<String, String>();

        String yxyApiYxUrl = SpringContextUtil.getCtx().getEnvironment().getProperty("yx.rest.api.yx.path");

        // 通知内容
        if (null == alert) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        if (alert.isEmpty()) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        String abbrAlert = StringUtils.abbreviate(alert, 50);

        returnMap.put("ALERT", abbrAlert);

        // 通知标题
        if (null == title) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        if (title.isEmpty()) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        returnMap.put("TITLE", title);

        // 验证推送开关是否开启
        String modelId = extra.get("modelId");

        List<Integer> role = new ArrayList<Integer>();
        for (String ta : tag_ands) {
            StringBuffer roleBuffer = new StringBuffer();
            // 转为char数组
            char[] ch = ta.toCharArray();
            // 得到大写字母
            for (int i = 0; i < ch.length; i++) {
                if (ch[i] >= 'A' && ch[i] <= 'Z') {
                    roleBuffer.append(ch[i]);
                }
            }
            switch (roleBuffer.toString()) {
            case "SCH":
                role.add(2);
                break;
            case "TEACHER":
                role.add(0);
                break;
            case "PARENTS":
                role.add(1);
                break;
            default:
                return;
            }
        }

        // 获取推送开关是否开启&能否发送推送
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("jpushName", modelId);
            formMap.put("jpushRole", role);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            restTemplate = new RestTemplate();
            JpushForCompRespModel httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/jpush/comp/app/switch",
                    formEntity, JpushForCompRespModel.class);

            if (!httpResult.isTure) { return; }
        } catch (Exception e) {
            LOGGER.info("获取推送开关接口异常：" + e.getMessage());
        }

        // 通知拓展数据
        String extraJson = "";

        try {
            extraJson = objectMapper.writeValueAsString(extra);
        } catch (JsonProcessingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            LOGGER.info("发送取消: 组装数据异常");
        }
        returnMap.put("EXTRA", extraJson);

        // tag用户
        if (null == tags) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }
        if (tags.isEmpty()) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }

        // tag_and数据
        if (null != tag_ands) {
            if (!tag_ands.isEmpty()) {
                if (tag_ands.size() > 20) {
                    LOGGER.info("发送取消: tags_and参数");
                    return;
                }
                returnMap.put("msgTag_and", StringUtils.join(tag_ands.toArray(), ","));
            }
        }

        returnMap.put("msgReceivers", StringUtils.join(tags.toArray(), ","));

        // 日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        returnMap.put("date", df.format(date));

        try {
            SpringContextUtil.getBean(RabbitTemplate.class).convertAndSend(RabbitConfig.JPUSH_FOR_NOTIFICATION,
                    returnMap);
        } catch (AmqpException e) {
            LOGGER.info("发送准备失败: RabbitMQ发送失败");
            return;
        }
        LOGGER.info("发送准备完毕: 通知消息数据组装成功，准备发送");
    }

    /**
     * 电子书包消息推送（通知）
     * 
     * @param alert（通知内容）
     * @param title（通知标题）
     * @param extra（扩展）—k,v
     * @param tags（接收tag）
     * @param tag_ands（接收tag_and关系）
     * @param date（定时发送时间）
     */
    public static void sendNotificationPack(String alert, String title, Map<String, String> extra, List<String> tags,
            List<String> tag_ands, Date date) {
        Map<String, String> returnMap = new HashMap<String, String>();

        // 通知内容
        if (null == alert) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        if (alert.isEmpty()) {
            LOGGER.info("发送取消: Notification参数alert为空");
            return;
        }
        String abbrAlert = StringUtils.abbreviate(alert, 50);

        returnMap.put("ALERT", abbrAlert);

        // 通知标题
        if (null == title) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        if (title.isEmpty()) {
            LOGGER.info("发送取消: Notification参数title为空");
            return;
        }
        returnMap.put("TITLE", title);

        // 通知拓展数据
        String extraJson = "";

        try {
            extraJson = objectMapper.writeValueAsString(extra);
        } catch (JsonProcessingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            LOGGER.info("发送取消: 组装数据异常");
        }
        returnMap.put("EXTRA", extraJson);

        // tag用户
        if (null == tags) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }
        if (tags.isEmpty()) {
            LOGGER.info("发送取消: tags接收者为空");
            return;
        }

        // tag_and数据
        if (null != tag_ands) {
            if (!tag_ands.isEmpty()) {
                if (tag_ands.size() > 20) {
                    LOGGER.info("发送取消: tags_and参数");
                    return;
                }
                returnMap.put("msgTag_and", StringUtils.join(tag_ands.toArray(), ","));
            }
        }

        returnMap.put("msgReceivers", StringUtils.join(tags.toArray(), ","));

        // 日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        returnMap.put("date", df.format(date));

        // 电子书包标识
        returnMap.put("flag", "epack");

        try {
            SpringContextUtil.getBean(RabbitTemplate.class).convertAndSend(RabbitConfig.JPUSH_FOR_NOTIFICATION,
                    returnMap);
        } catch (AmqpException e) {
            LOGGER.info("发送准备失败: RabbitMQ发送失败");
            return;
        }
        LOGGER.info("发送准备完毕: 通知消息数据组装成功，准备发送");
    }
}
